package com.example.demoddd.application.in.rest.controller;


import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demoddd.application.dto.Results;
import com.example.demoddd.application.dto.UserDto;
import com.example.demoddd.application.services.LoginApplicationService;
import com.example.demoddd.application.services.UserServiceApplicationService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@RestController
@RequiredArgsConstructor
public class LoginController {
    private final UserServiceApplicationService userServiceApplicationService;
    private final LoginApplicationService loginApplicationService;

    //private final AuthenticationManager authenticationManager;
    @PostMapping("/login")
    public Results doLogin(@RequestBody UserDto userDto) {

        return loginApplicationService.doLogin(userDto);
    }

    /**
     * 前端需要设置倒计时任务 在token失效前调用, 建议提前 10到30秒
     *
     * @return
     */
    @PostMapping("/refreshToken")
    public Results refreshToken() {

        return loginApplicationService.refreshToken();
    }


    private final ApplicationContext applicationContext;


    @PostMapping("/scanMethodsWithAnnotation")
    public Results scanMethodsWithAnnotation() {

        List<String> permissions = new ArrayList<>();
        //扫描类使用hutool
        Set<Class<?>> classes1 = ClassUtil.scanPackage("com.example");
        for (Class candidate : classes1) {

            for (Method method : candidate.getDeclaredMethods()) {
                // 检查方法是否包含自定义注解
                if (method.isAnnotationPresent(PreAuthorize.class)) {
                    System.out.println("Found method with custom annotation: " + method.getName());
                    // 这里可以添加更多的逻辑，例如调用方法或记录方法信息
                    PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
                    String value = annotation.value();
                    String permission = StrUtil.subBetween(value, "'");

                    permissions.add(permission);
                }
            }

        }


        System.out.println("扫描到的注释");
        System.out.println(permissions);

        return new Results<>();
    }
}

